package com.techsoul.module.tms.controller;

import com.techsoul.common.core.exception.BusinessException;
import com.techsoul.common.core.exception.ExcelException;
import com.techsoul.common.core.pojo.Result;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.core.util.poi.ExcelImport;
import com.techsoul.common.log.annotation.Log;
import com.techsoul.common.log.enums.OperationTypeEnum;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.basic.mapper.CustomerConsigneeMapper;
import com.techsoul.module.basic.mapper.WarehouseMapper;
import com.techsoul.module.basic.pojo.entity.Customer;
import com.techsoul.module.basic.pojo.entity.CustomerConsignee;
import com.techsoul.module.basic.pojo.entity.Warehouse;
import com.techsoul.module.basic.pojo.param.SuspiciousItemSaveParam;
import com.techsoul.module.basic.pojo.vo.WarehouseVo;
import com.techsoul.module.order.pojo.entity.PurchaseOrder;
import com.techsoul.module.order.pojo.entity.PurchaseOrderItem;
import com.techsoul.module.pms.enmus.LocationStatusEnum;
import com.techsoul.module.pms.enmus.WmsOutStatusEnum;
import com.techsoul.module.pms.mapper.*;
import com.techsoul.module.pms.pojo.entity.*;
import com.techsoul.module.pms.pojo.param.TbWmsMaterialDeliverySaveParam;
import com.techsoul.module.pms.pojo.vo.TbWmsMaterialDeliveryLineVo;
import com.techsoul.module.pms.pojo.vo.TbWmsMaterialDeliveryVo;
import com.techsoul.module.pms.pojo.vo.TbWmsMaterialReceiptVo;
import com.techsoul.module.pms.service.ITbWmsMaterialDeliveryService;
import com.techsoul.module.pms.service.ITbWmsMaterialReceiptLineService;
import com.techsoul.module.tms.pojo.entity.TFoFreightOrder;
import com.techsoul.module.tms.pojo.entity.TFoFreightOrderItem;
import com.techsoul.module.tms.pojo.entity.iCustomer;
import com.techsoul.module.tms.pojo.param.*;
import com.techsoul.module.tms.pojo.vo.DispatchImportOrderItemVo;
import com.techsoul.module.tms.pojo.vo.TFoTransitRouteVo;
import com.techsoul.module.tms.service.IExpressService;
import com.techsoul.module.tms.service.ITFoFreightOrderItemService;
import com.techsoul.module.tms.service.ITFoFreightOrderService;
import com.techsoul.module.tms.service.ITFoTransitRouteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.*;

/**
 * 运单明细 Controller
 *
 * @author liuen
 * @date 2023-05-29
 */
@Api(tags = "运单明细")
@Slf4j
@RestController
@RequestMapping("/tms/tFoFreightOrderItem")
public class TFoFreightOrderItemController {

    @Autowired
    private Result result;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IExpressService iExpressService;
    @Autowired
    private ITbWmsMaterialDeliveryService iTbWmsMaterialDeliveryService;
    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TbWmsMaterialDeliveryLineMapper tbWmsMaterialDeliveryLineMapper;
    @Autowired
    private WarehouseMapper warehouseMapper;


    @Autowired
    private TbWmsMaterialReceiptMapper tbWmsMaterialReceiptMapper;
    @Autowired
    private TbWmsMaterialReceiptLineMapper tbWmsMaterialReceiptLineMapper;
    @Autowired
    private TbWmsMaterialInLocationMapper tbWmsMaterialInLocationapper;
    @Autowired
    private TbWmsMaterialDeliveryMapper tbWmsMaterialDeliveryMapper;
    @Autowired
    private ITFoFreightOrderItemService service;
    @Autowired
    private ITFoTransitRouteService iTFoTransitRouteService;

    @Autowired
    private CustomerConsigneeMapper customerConsigneeMapper;
    @Autowired
    private ITbWmsMaterialReceiptLineService receiptLineService;

    @Autowired
    private ITFoFreightOrderService tFoFreightOrderService;
    @ApiOperation("新增")
    @Log(title = "运单明细", operationType = OperationTypeEnum.INSERT)
    @PreAuthorize("hasAnyAuthority('tms:tFoFreightOrderItem:insert')")
    @PostMapping
    public Result insert(@Valid @RequestBody TFoFreightOrderItemSaveParam params) {
        return result.success(this.service.insert(params));
    }

    @ApiOperation("批量删除（多个用逗号隔开）")
    @Log(title = "运单明细", operationType = OperationTypeEnum.DELETE)
    @PreAuthorize("hasAnyAuthority('tms:tFoFreightOrderItem:delete')")
    @DeleteMapping("/{ids}")
    public Result batchDelete(@PathVariable String[] ids) {
        return result.success(this.service.batchDelete(Arrays.asList(ids)));
    }

    @ApiOperation("修改")
    @Log(title = "运单明细", operationType = OperationTypeEnum.UPDATE)
    @PreAuthorize("hasAnyAuthority('tms:tFoFreightOrderItem:update')")
    @PutMapping
    public Result update(@Valid @RequestBody TFoFreightOrderItemSaveParam params) {
        return result.success(this.service.update(params));
    }
    @ApiOperation("处理可疑")
    @Log(title = "处理可疑", operationType = OperationTypeEnum.UPDATE)
    @PreAuthorize("hasAnyAuthority('tms:tFoFreightOrderItem:resolveSuspicious')")
    @PostMapping("/resolveSuspicious")
    public Result resolveSuspicious(@Valid @RequestBody SuspiciousItemSaveParam params) {
        return result.success(this.service.resolveSuspicious(params));
    }
    @ApiOperation("移入可疑")
    @Log(title = "移入可疑", operationType = OperationTypeEnum.UPDATE)
    @PreAuthorize("hasAnyAuthority('tms:tFoFreightOrderItem:update')")
    @PostMapping("/moveToSuspicious")
    public Result moveToSuspicious(@Valid @RequestBody TFoFreightOrderItemSaveParam params) {
        return result.success(this.service.moveToSuspicious(params));
    }
    @ApiOperation("溢库调拨移库")
    //@PreAuthorize("hasAnyAuthority('web:tbWmsMaterialInLocation:moveToRentWarehouse')")
    @PostMapping("/moveToRentWarehouse")
    public Result moveToRentWarehouse(@Valid @RequestBody TFoFreightOrderItemSaveParam params) {
        List<String> ids = params.getVehicleInLocIds();
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        String moveToWarehouseCode = params.getMoveToWarehouseCode();
        WarehouseVo moveTo = this.warehouseMapper.findById(moveToWarehouseCode);
        List<TbWmsMaterialDelivery> deliverys = new ArrayList<TbWmsMaterialDelivery>();
        List<TbWmsMaterialDeliveryLine> items = new ArrayList<TbWmsMaterialDeliveryLine>();
        List<TbWmsMaterialReceipt> tbWmsMaterialReceipts = new ArrayList<TbWmsMaterialReceipt>();
        List<Map<String,String>> tbWmsMaterialReceiptsMap = new ArrayList<Map<String,String>>();
        Map<String,String> map = new HashMap<String,String>();
        List<TbWmsMaterialReceiptLine> tbWmsMaterialReceiptLines = new ArrayList<TbWmsMaterialReceiptLine>();
        List<TbWmsMaterialDelivery> inwhdeliverys = new ArrayList<TbWmsMaterialDelivery>();
        List<TbWmsMaterialDeliveryLine> inwhitems = new ArrayList<TbWmsMaterialDeliveryLine>();
        WarehouseVo towarehouse = this.warehouseMapper.findById(params.getMoveToWarehouseCode());
        WarehouseVo frwarehouse = null;
        for(int i=0;i<ids.size();i++){

            TbWmsMaterialReceiptLine receiptline =
                    this.tbWmsMaterialReceiptLineMapper.selectById(ids.get(i));

            receiptline.setStageNo(towarehouse.getId());
            receiptline.setStatus("move");
            receiptline.preUpdate(user.getId());

            this.tbWmsMaterialReceiptLineMapper.updateById(receiptline);
            tbWmsMaterialReceiptLines.add(receiptline);
            TbWmsMaterialReceipt receipt=
                    this.tbWmsMaterialReceiptMapper.selectById(receiptline.getReceiptId());
            map.put(receipt.getId(),receipt.getWarehouseCode());
            receipt.setWarehouseCode(towarehouse.getId());
            receipt.setStatus("move");
            receipt.preUpdate(user.getId());
            tbWmsMaterialReceipts.add(receipt);
            tbWmsMaterialReceiptsMap.add(map);
            this.tbWmsMaterialReceiptMapper.updateById(receipt);
            List<TbWmsMaterialInLocation> tbWmsMaterialInLocations
                    = this.tbWmsMaterialInLocationapper.findByReciptLineId(receiptline.getId());


             frwarehouse = this.warehouseMapper.findById(receipt.getWarehouseCode());
            //参数需要：params.getMoveToWarehouseCode()
      //      TbWmsMaterialDelivery delivery =
              //     this.receiptLineService.generateDelivery(receiptline.getOrderNo(),receiptline,frwarehouse,towarehouse,user,receipt);
            //最后需要送货的收货人
            //    CustomerConsignee customerConsignee = this.customerConsigneeMapper.selectById(params.getConsignee());
          //  TbWmsMaterialReceipt tbWmsMaterialReceipt =
               //     this.receiptLineService.generateMoveInWarehouseReceipt(receiptline.getOrderNo(),receiptline,frwarehouse,towarehouse,user,receipt);
            //   TbWmsMaterialDelivery inWarehouseDelivery =
            //         this.receiptLineService.generateMoveInWarehouseDelivery(receiptline,frwarehouse,null,user,receipt);


          //   deliverys.add(delivery);
//

           // TbWmsMaterialDeliveryLine deliveryLine =
              //      this.receiptLineService.generateDeliveryLine(receiptline.getOrderNo(),receiptline,frwarehouse,towarehouse,user,delivery);
          //  TbWmsMaterialReceiptLine tbWmsMaterialReceiptLine =
                //    this.receiptLineService.generateMoveInWarehouseReceiptLine(receiptline.getOrderNo(),receiptline,frwarehouse,towarehouse,user,tbWmsMaterialReceipt);
            //   TbWmsMaterialDeliveryLine inWarehouseDeliveryLine =
            //       this.receiptLineService.generateMoveInWarehouseDeliveryLine(receiptline,towarehouse,null,user,inWarehouseDelivery);

           if(tbWmsMaterialInLocations!=null&&tbWmsMaterialInLocations.size()>0){
               TbWmsMaterialInLocation tbWmsMaterialInLocation = (TbWmsMaterialInLocation)tbWmsMaterialInLocations.get(0);
              // tbWmsMaterialInLocation.setWarehouseCode(towarehouse.getId());
               tbWmsMaterialInLocation.setIsValid("0");
               tbWmsMaterialInLocation.preUpdate(user.getId());
               this.tbWmsMaterialInLocationapper.updateById(tbWmsMaterialInLocation);
            //   receiptline.setIsValid("0");
              // receipt.setIsValid("0");
           //    receipt.preUpdate(user.getId());
           //    receiptline.preUpdate(user.getId());
             //  this.tbWmsMaterialReceiptLineMapper.updateById(receiptline);
            //   this.tbWmsMaterialReceiptMapper.updateById(receipt);
           }
          //  items.add(deliveryLine);

        }
        //新建运单需要在service
        List<TFoFreightOrder> orders = new ArrayList<TFoFreightOrder>();
        List<TFoFreightOrderItem> dispatchItems = this.service.generateMoveTrDispatch(tbWmsMaterialReceipts,tbWmsMaterialReceiptLines,params,user,orders,moveToWarehouseCode,tbWmsMaterialReceiptsMap);
        this.iExpressService.genFreightOrderAndItem(orders,dispatchItems, params.getDriverNos(),params.getCarrierNo(),frwarehouse.getId(),towarehouse.getId(),params.getRouteType());


        return result.success();
    }


    @ApiOperation("移库到包装厂或属地委改厂")
    @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialInLocation:moveDispatch')")
    @PostMapping("/moveDispatch")
    public Result moveDispatch(@Valid @RequestBody TFoFreightOrderItemSaveParam params) {
        List<String> ids = params.getVehicleInLocIds();
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        String moveToWarehouseCode = params.getMoveToWarehouseCode();
        //  WarehouseVo moveTo = this.warehouseMapper.findById(moveToWarehouseCode);
        List<TbWmsMaterialDelivery> deliverys = new ArrayList<TbWmsMaterialDelivery>();

        List<TbWmsMaterialDelivery> finaldeliverys = new ArrayList<TbWmsMaterialDelivery>();
        List<TbWmsMaterialDeliveryLine> items = new ArrayList<TbWmsMaterialDeliveryLine>();
        List<TbWmsMaterialReceipt> tbWmsMaterialReceipts = new ArrayList<TbWmsMaterialReceipt>();
        List<TbWmsMaterialReceiptLine> tbWmsMaterialReceiptLines = new ArrayList<TbWmsMaterialReceiptLine>();
        List<TbWmsMaterialDelivery> inwhdeliverys = new ArrayList<TbWmsMaterialDelivery>();
        List<TbWmsMaterialDeliveryLine> finalitems = new ArrayList<TbWmsMaterialDeliveryLine>();
        WarehouseVo towarehouse = this.warehouseMapper.findById(params.getMoveToWarehouseCode());
        WarehouseVo frwarehouse = null;
        for(int i=0;i<ids.size();i++){
            TbWmsMaterialDeliveryLine line = this.tbWmsMaterialDeliveryLineMapper.selectById(ids.get(i));
            TbWmsMaterialDelivery centerdelivery = this.tbWmsMaterialDeliveryMapper.selectById(line.getDeliveryId());
            WarehouseVo finalDestWarehouse = this.warehouseMapper.findById(line.getDeliveryWarehouseCode());
            if(StringUtils.isNull(line.getMaterialVehicleInLocationId())){
                throw new BusinessException("取货库位没有定义，请先锁定取货库位");
            }
            TbWmsMaterialInLocation tbWmsMaterialInLocation
                    = this.tbWmsMaterialInLocationapper.selectById(line.getMaterialVehicleInLocationId());
            //    tbWmsMaterialInLocation.setQuantity(0.0);
            //     tbWmsMaterialInLocation.setStatus(LocationStatusEnum.empty.getValue());
            //      tbWmsMaterialInLocation.preUpdate(user.getId());
            //       this.tbWmsMaterialInLocationapper.updateById(tbWmsMaterialInLocation);
            TbWmsMaterialReceiptLine receiptline =
                    this.tbWmsMaterialReceiptLineMapper.selectById(tbWmsMaterialInLocation.getReceivedLineId());
            TbWmsMaterialReceipt receipt =
                    this.tbWmsMaterialReceiptMapper.selectById(receiptline.getReceiptId());
            frwarehouse = this.warehouseMapper.findById(receipt.getWarehouseCode());

            //参数需要：params.getMoveToWarehouseCode()
            TbWmsMaterialDelivery delivery =  new TbWmsMaterialDelivery();
            BeanUtils.copyProperties(centerdelivery,delivery);
            delivery.setCustomerNo(centerdelivery.getCustomerNo());
            delivery.setCustomerName(centerdelivery.getCustomerName());
            delivery.setWarehouseCode(frwarehouse.getId());
            delivery.setConsigneeName(towarehouse.getWarehouserName());
            delivery.setConsigneeAddress(towarehouse.getAddress());
            delivery.setConsigneePhoneNo(towarehouse.getContactPhone());
            delivery.setConsigneeCity(towarehouse.getCity());
            delivery.setConsignee(towarehouse.getId());
            delivery.setOrderNo(line.getOrderNo());
            if(params.getStatus()!=null){
                delivery.setStatus(params.getStatus());
                centerdelivery.setStatus(params.getStatus());
            }

            //   this.receiptLineService.generateDelivery(receiptline,frwarehouse,towarehouse,user,receipt);
            //包装厂或委改厂出库单
            TbWmsMaterialDelivery finaldelivery =
                    this.receiptLineService.generateDelivery(line.getOrderNo(),receiptline,towarehouse,finalDestWarehouse,user,receipt,centerdelivery);
            //最后需要送货的收货人
            //    CustomerConsignee customerConsignee = this.customerConsigneeMapper.selectById(params.getConsignee());
            TbWmsMaterialReceipt tbWmsMaterialReceipt =
                    this.receiptLineService.generateMoveInWarehouseReceipt(line.getOrderNo(),receiptline,frwarehouse,towarehouse,user,receipt);
            //   TbWmsMaterialDelivery inWarehouseDelivery =
            //         this.receiptLineService.generateMoveInWarehouseDelivery(receiptline,frwarehouse,null,user,receipt);

            finaldeliverys.add(finaldelivery);
            deliverys.add(delivery);


            TbWmsMaterialDeliveryLine deliveryLine = new TbWmsMaterialDeliveryLine();
            deliveryLine.setDeparture(frwarehouse.getCity())
                    .setDeliveryId(centerdelivery.getId())
                    .setDestination(towarehouse.getCity())
                    .setCustomerName(centerdelivery.getCustomerName())
                    .setCustomerNo(centerdelivery.getCustomerNo())
                    .setOrderNo(centerdelivery.getOrderNo())
                    .setSite(towarehouse.getOrgId())
                    .setOrderNo(line.getOrderNo())
                    .setMaterialNo(line.getMaterialNo())
                    .setMaterialName(line.getMaterialName())
                    .setDeliveryWarehouseCode(towarehouse.getId())
                    .setDeliveryWarehouseName(towarehouse.getWarehouseFullName())
                    .setDeliveryWarehouseType(towarehouse.getWarehouseType());

            line.setDeliveryWarehouseCode(towarehouse.getId())
                    .setDeliveryWarehouseName(towarehouse.getWarehouseFullName())
                    .setDeliveryWarehouseType(towarehouse.getWarehouseType());
            //      this.receiptLineService.generateDeliveryLine(receiptline,frwarehouse,towarehouse,user,delivery);
//包装厂或委改厂出库单 明细
            TbWmsMaterialDeliveryLine finaldeliveryLine =
                    this.receiptLineService.generateDeliveryLine(line.getOrderNo(),receiptline,towarehouse,finalDestWarehouse,user,delivery,line);
            TbWmsMaterialReceiptLine tbWmsMaterialReceiptLine =
                    this.receiptLineService.generateMoveInWarehouseReceiptLine(line.getOrderNo(),receiptline,frwarehouse,towarehouse,user,tbWmsMaterialReceipt);
            //   TbWmsMaterialDeliveryLine inWarehouseDeliveryLine =
            //       this.receiptLineService.generateMoveInWarehouseDeliveryLine(receiptline,towarehouse,null,user,inWarehouseDelivery);

            deliveryLine.setReceivedLineId(tbWmsMaterialReceiptLine.getId());
            deliveryLine.setCaseNo(finaldeliveryLine.getId());
            finalitems.add(finaldeliveryLine);
            items.add(deliveryLine);
            tbWmsMaterialInLocation.setIsValid("0");
            tbWmsMaterialInLocation.preUpdate(user.getId());
            this.tbWmsMaterialInLocationapper.updateById(tbWmsMaterialInLocation);
            line.setStatus(WmsOutStatusEnum.shipPlaned.getValue());
            line.preUpdate(user.getId());
            this.tbWmsMaterialDeliveryLineMapper.updateById(line);
            centerdelivery.setStatus(WmsOutStatusEnum.shipPlaned.getValue());
            centerdelivery.preUpdate(user.getId());
            this.tbWmsMaterialDeliveryMapper.updateById(centerdelivery);
        }
        //新建运单需要在service
        List<TFoFreightOrder> orders = new ArrayList<TFoFreightOrder>();
        List<TFoFreightOrderItem> dispatchItems = this.service.generateMoveDispatch(deliverys,items,params,user,orders,moveToWarehouseCode);
        //  List<TFoFreightOrderItem> dispatchFinalItems = this.service.generateMoveDispatch(finaldeliverys,finalitems,params,user,orders);
        this.iExpressService.genFreightOrderAndItem(orders,dispatchItems, params.getDriverNos(),params.getCarrierNo(),frwarehouse.getId(),towarehouse.getId(),params.getRouteType());


        return result.success();
    }

    private String moveDispatch2(TFoFreightOrderItemSaveParam params) {
        List<String> ids = params.getVehicleInLocIds();
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        String moveToWarehouseCode = params.getMoveToWarehouseCode();
        //  WarehouseVo moveTo = this.warehouseMapper.findById(moveToWarehouseCode);
        List<TbWmsMaterialDelivery> deliverys = new ArrayList<TbWmsMaterialDelivery>();

        List<TbWmsMaterialDelivery> finaldeliverys = new ArrayList<TbWmsMaterialDelivery>();
        List<TbWmsMaterialDeliveryLine> items = new ArrayList<TbWmsMaterialDeliveryLine>();
        List<TbWmsMaterialReceipt> tbWmsMaterialReceipts = new ArrayList<TbWmsMaterialReceipt>();
        List<TbWmsMaterialReceiptLine> tbWmsMaterialReceiptLines = new ArrayList<TbWmsMaterialReceiptLine>();
        List<TbWmsMaterialDelivery> inwhdeliverys = new ArrayList<TbWmsMaterialDelivery>();
        List<TbWmsMaterialDeliveryLine> finalitems = new ArrayList<TbWmsMaterialDeliveryLine>();
        WarehouseVo towarehouse = this.warehouseMapper.findById(params.getMoveToWarehouseCode());
        WarehouseVo frwarehouse = null;
        List<String> list = new ArrayList<>();
        for(int i=0;i<ids.size();i++){
            TbWmsMaterialDeliveryLine line = this.tbWmsMaterialDeliveryLineMapper.selectById(ids.get(i));
            TbWmsMaterialDelivery centerdelivery = this.tbWmsMaterialDeliveryMapper.selectById(line.getDeliveryId());
            WarehouseVo finalDestWarehouse = this.warehouseMapper.findById(line.getDeliveryWarehouseCode());
            if(StringUtils.isNull(line.getMaterialVehicleInLocationId())){
                throw new BusinessException("取货库位没有定义，请先锁定取货库位");
            }
            TbWmsMaterialInLocation tbWmsMaterialInLocation
                    = this.tbWmsMaterialInLocationapper.selectById(line.getMaterialVehicleInLocationId());
            //    tbWmsMaterialInLocation.setQuantity(0.0);
            //     tbWmsMaterialInLocation.setStatus(LocationStatusEnum.empty.getValue());
            //      tbWmsMaterialInLocation.preUpdate(user.getId());
            //       this.tbWmsMaterialInLocationapper.updateById(tbWmsMaterialInLocation);
            TbWmsMaterialReceiptLine receiptline =
                    this.tbWmsMaterialReceiptLineMapper.selectById(tbWmsMaterialInLocation.getReceivedLineId());
            TbWmsMaterialReceipt receipt =
                    this.tbWmsMaterialReceiptMapper.selectById(receiptline.getReceiptId());
            frwarehouse = this.warehouseMapper.findById(receipt.getWarehouseCode());

            //参数需要：params.getMoveToWarehouseCode()
            TbWmsMaterialDelivery delivery =  new TbWmsMaterialDelivery();
            BeanUtils.copyProperties(centerdelivery,delivery);
            delivery.setCustomerNo(centerdelivery.getCustomerNo());
            delivery.setCustomerName(centerdelivery.getCustomerName());
            delivery.setWarehouseCode(frwarehouse.getId());
            delivery.setConsigneeName(towarehouse.getWarehouserName());
            delivery.setConsigneeAddress(towarehouse.getAddress());
            delivery.setConsigneePhoneNo(towarehouse.getContactPhone());
            delivery.setConsigneeCity(towarehouse.getCity());
            delivery.setConsignee(towarehouse.getId());
            delivery.setOrderNo(line.getOrderNo());
            if(params.getStatus()!=null){
                delivery.setStatus(params.getStatus());
                centerdelivery.setStatus(params.getStatus());
            }

            //   this.receiptLineService.generateDelivery(receiptline,frwarehouse,towarehouse,user,receipt);
            //包装厂或委改厂出库单
            TbWmsMaterialDelivery finaldelivery =
                    this.receiptLineService.generateDelivery(line.getOrderNo(),receiptline,towarehouse,finalDestWarehouse,user,receipt,centerdelivery);
            //最后需要送货的收货人
            //    CustomerConsignee customerConsignee = this.customerConsigneeMapper.selectById(params.getConsignee());
            TbWmsMaterialReceipt tbWmsMaterialReceipt =
                    this.receiptLineService.generateMoveInWarehouseReceipt(line.getOrderNo(),receiptline,frwarehouse,towarehouse,user,receipt);
            //   TbWmsMaterialDelivery inWarehouseDelivery =
            //         this.receiptLineService.generateMoveInWarehouseDelivery(receiptline,frwarehouse,null,user,receipt);

            finaldeliverys.add(finaldelivery);
            deliverys.add(delivery);


            TbWmsMaterialDeliveryLine deliveryLine = new TbWmsMaterialDeliveryLine();
            deliveryLine.setDeparture(frwarehouse.getCity())
                    .setDeliveryId(centerdelivery.getId())
                    .setDestination(towarehouse.getCity())
                    .setCustomerName(centerdelivery.getCustomerName())
                    .setCustomerNo(centerdelivery.getCustomerNo())
                    .setOrderNo(centerdelivery.getOrderNo())
                    .setSite(towarehouse.getOrgId())
                    .setOrderNo(line.getOrderNo())
                    .setMaterialNo(line.getMaterialNo())
                    .setMaterialName(line.getMaterialName())
                    .setDeliveryWarehouseCode(towarehouse.getId())
                    .setDeliveryWarehouseName(towarehouse.getWarehouseFullName())
                    .setDeliveryWarehouseType(towarehouse.getWarehouseType());

            line.setDeliveryWarehouseCode(towarehouse.getId())
                    .setDeliveryWarehouseName(towarehouse.getWarehouseFullName())
                    .setDeliveryWarehouseType(towarehouse.getWarehouseType());
            //      this.receiptLineService.generateDeliveryLine(receiptline,frwarehouse,towarehouse,user,delivery);
//包装厂或委改厂出库单 明细
            TbWmsMaterialDeliveryLine finaldeliveryLine =
                    this.receiptLineService.generateDeliveryLine(line.getOrderNo(),receiptline,towarehouse,finalDestWarehouse,user,delivery,line);
            list.add(finaldeliveryLine.getId());
            TbWmsMaterialReceiptLine tbWmsMaterialReceiptLine =
                    this.receiptLineService.generateMoveInWarehouseReceiptLine(line.getOrderNo(),receiptline,frwarehouse,towarehouse,user,tbWmsMaterialReceipt);
            //   TbWmsMaterialDeliveryLine inWarehouseDeliveryLine =
            //       this.receiptLineService.generateMoveInWarehouseDeliveryLine(receiptline,towarehouse,null,user,inWarehouseDelivery);

            deliveryLine.setReceivedLineId(tbWmsMaterialReceiptLine.getId());
            deliveryLine.setCaseNo(finaldeliveryLine.getId());
            finalitems.add(finaldeliveryLine);
            items.add(deliveryLine);
            tbWmsMaterialInLocation.setIsValid("0");
            tbWmsMaterialInLocation.preUpdate(user.getId());
            this.tbWmsMaterialInLocationapper.updateById(tbWmsMaterialInLocation);
            line.setStatus(WmsOutStatusEnum.shipPlaned.getValue());
            line.preUpdate(user.getId());
            this.tbWmsMaterialDeliveryLineMapper.updateById(line);
            centerdelivery.setStatus(WmsOutStatusEnum.shipPlaned.getValue());
            centerdelivery.preUpdate(user.getId());
            this.tbWmsMaterialDeliveryMapper.updateById(centerdelivery);
        }
        //新建运单需要在service
        List<TFoFreightOrder> orders = new ArrayList<TFoFreightOrder>();
        List<TFoFreightOrderItem> dispatchItems = this.service.generateMoveDispatch(deliverys,items,params,user,orders,moveToWarehouseCode);
        //  List<TFoFreightOrderItem> dispatchFinalItems = this.service.generateMoveDispatch(finaldeliverys,finalitems,params,user,orders);
        this.iExpressService.genFreightOrderAndItem(orders,dispatchItems, params.getDriverNos(),params.getCarrierNo(),frwarehouse.getId(),towarehouse.getId(),params.getRouteType());


        return list.get(0);
    }



    @ApiOperation("确认")
    @PreAuthorize("hasAnyAuthority('tms:tFoFreightOrderItem:update')")
    @PostMapping("/confirm/{id}")
    public Result confirm(@PathVariable("id") String id) {
        return result.success(this.service.confirm(id));
    }

    @ApiOperation("详情")
    @PreAuthorize("hasAnyAuthority('tms:tFoFreightOrderItem:search')")
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") String id) {
        return result.success(this.service.findById(id));
    }

    @ApiOperation("列表")
    @PreAuthorize("hasAnyAuthority('tms:tFoFreightOrderItem:search')")
    @PostMapping("/search")
    public Result findAll(@RequestBody TFoFreightOrderItemSearchParam params) {
        return result.success(this.service.findAll(params));
    }
    @ApiOperation("随车工具出库单和运单生成")
    @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialDelivery:insertToolsAll')")
    @PostMapping("/insertToolsAll")
    public Result insertToolsAll(@RequestBody TbWmsMaterialDeliverySaveParam params){
        List<TbWmsMaterialDeliveryLine> tbWmsMaterialDeliveryLines = this.iTbWmsMaterialDeliveryService.insertALLToolsItem(params);


        TFoFreightOrder order = new TFoFreightOrder();
        List<TFoFreightOrderItem> items=new ArrayList<TFoFreightOrderItem>();
        List<String> driverNos = params.getDriverNos();
        String carrierNo = params.getCarrierNo();
        this.tFoFreightOrderService.
                generateFreightOrderFromDelivery(params,tbWmsMaterialDeliveryLines,order,items);

        List<TFoFreightOrder> orders = new  ArrayList<TFoFreightOrder>();
        orders.add(order);
        //this.iExpressService.genFreightOrderAndItem(orders,items,driverNos,carrierNo,order.getDepartPort(),order.getDestPort());

        return result.success("success");
    }
    @ApiOperation("生成随车工具取货任务")
//   @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialDeliveryLine:generateArForDelivery')")
    @PostMapping("/generateFreightAccessaryFromDelivery/{ids}")
    public Result generateFreightAccessaryFromDelivery(@RequestBody TFoFreightOrderSaveParam params, @PathVariable String[] ids) {
        for(int i=0; i <ids.length;i++) {
            String id = (String)ids[i];
            TbWmsMaterialDeliveryLineVo tbWmsMaterialDeliveryLineVo = this.tbWmsMaterialDeliveryLineMapper.findById(id);
            TbWmsMaterialDeliveryVo tbWmsMaterialDeliveryVo = this.tbWmsMaterialDeliveryMapper.findById(tbWmsMaterialDeliveryLineVo.getDeliveryId());
              TFoFreightOrder order = new TFoFreightOrder();
              TFoFreightOrderItem item=new TFoFreightOrderItem();

            this.tFoFreightOrderService.
                    generateFreightOrderFromDelivery(params,tbWmsMaterialDeliveryLineVo,tbWmsMaterialDeliveryVo
                            ,order,item);

            this.iExpressService.genFreightOrderAndItem(order,item);
        }
        return result.success("success");
    }

    @ApiOperation("生成配送运单")
//   @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialDeliveryLine:generateArForDelivery')")
    @PostMapping("/generateFreightOrderFromDelivery/{ids}")
    public Result generateFreightOrderFromDelivery(@RequestBody TFoFreightOrderSaveParam params, @PathVariable String[] ids) {
            for(int i=0; i <ids.length;i++) {
            String id = (String)ids[i];
            TbWmsMaterialDeliveryLineVo tbWmsMaterialDeliveryLineVo = this.tbWmsMaterialDeliveryLineMapper.findById(id);
            TbWmsMaterialDeliveryVo tbWmsMaterialDeliveryVo = this.tbWmsMaterialDeliveryMapper.findById(tbWmsMaterialDeliveryLineVo.getDeliveryId());
         //   TFoFreightOrder order = new TFoFreightOrder();
         //   TFoFreightOrderItem item=new TFoFreightOrderItem();
            PurchaseOrder order = new PurchaseOrder();
            PurchaseOrderItem item = new PurchaseOrderItem();
            this.tFoFreightOrderService.
                        generateFreightOrderFromDelivery(params,tbWmsMaterialDeliveryLineVo,tbWmsMaterialDeliveryVo
                                ,order,item);

            //更新运单表的IsValid为1；
            this.iExpressService.genPurchaseOrderAndItem(order,item,tbWmsMaterialDeliveryLineVo);
            //this.iExpressService.genPurchaseOrderAndItem(order,item);
        }
        return result.success("success");
    }

    @ApiOperation("订单处理中心导入发货单-决定承运人")
    //PreAuthorize("hasAnyAuthority('web:tbWmsLocation:insert')")
    @PostMapping("/importDataWithCarrier")
    public Result importDataWithCarrier(MultipartFile file) {
            List<DispatchImportOrderItemVo> dataList = null;
            StringBuilder successMsg = new StringBuilder();
            StringBuilder failureMsg = new StringBuilder();
            TFoFreightOrderItemSaveParam params = new TFoFreightOrderItemSaveParam();
            UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
            Integer successNum = 0;
            Integer failureNum = 0;
            String str = "";
            try {
                ExcelImport excelImport = new ExcelImport(file, 1, 0);
                dataList = excelImport.getDataList(DispatchImportOrderItemVo.class);
            } catch (Exception e) {
                log.error("获取数据信息失败!");
                throw new ExcelException("获取数据信息失败!");
            }
            if (ListUtils.isEmpty(dataList)) {
                throw new ExcelException("导入数据不能为空！");
            }
            for (DispatchImportOrderItemVo data : dataList) {
                try {
                    PurchaseOrderItem ent = new PurchaseOrderItem();
                    org.springframework.beans.BeanUtils.copyProperties(data, ent);
                    ent.setVehicleLoadType(data.getVehicleLoadType());
                    ent.setConsigneeName(data.getConsigneeName());

                    // 验证数据是否已经出库（委改）
                    TbWmsMaterialDeliveryLine line = this.tbWmsMaterialDeliveryLineMapper.findBySapOrderNo2(data.getPickupVoucherList(), data.getVinNo(),"remodel","outed");
                    // 验证数据是否已经出库（委改）
                    TbWmsMaterialDeliveryLine line2 = this.tbWmsMaterialDeliveryLineMapper.findBySapOrderNo2(data.getPickupVoucherList(), data.getVinNo(),"remodel","remodel");
                    // 验证数据是否已经出库（包装厂）
                    TbWmsMaterialDeliveryLine line1 = this.tbWmsMaterialDeliveryLineMapper.findBySapOrderNo2(data.getPickupVoucherList(), data.getVinNo(),"packing","outed");
                    // 验证入库里是否存在
                    TbWmsMaterialReceiptVo receiptVo = this.tbWmsMaterialReceiptMapper.findByVinNo(data.getVinNo());


                    if (line == null && line1 == null && receiptVo == null) {
                        this.service.saveToExceptions(data, ent, sysUser);
                        continue;
                    }
                    TFoTransitRouteVo routVo = this.getCarrier(data);
                    if (routVo == null) {
                        String msg = "<br/>导入失败：承运商" + data.getCarrierName() + "，没有配置路线;";
                        successMsg.append(msg);
                        break;
                    }

                    WarehouseVo warehouseVo = this.warehouseMapper.findById(routVo.getWarehouseId());
                    iCustomer cust1
                            = this.iExpressService.selectByCustomerId(data.getCustomerNo());

                    // 查到委改厂有数据。更新出库数据
                    if(line!=null){
                        this.service.updateToDelivery(sysUser,receiptVo,line);
                        line = null;
                    }

                    line = line2;

                    //新增出库单。并修改入库单状态和库存状态
                    if (receiptVo != null && line == null && line1 == null) {
                        str = this.service.saveToDelivery(data, sysUser, receiptVo);
                    }
                    if(StringUtils.isNull(cust1)){
                        cust1 = new iCustomer();
                        cust1.setId(data.getCustomerNo()).preInsert(sysUser.getId());
                        cust1.setCustomerName(data.getDepartureUnit());
                        cust1.setCustomerType("warehouse");
                        cust1.setIsValid("1");
                        cust1.setCreateDate(new Date());
                        cust1.setUpdateDate(cust1.getCreateDate());
                        this.iExpressService.createCustomer(cust1);
                    }

                    // 外借或者维修无法出库
                    if (str.equals("no")) {
                        continue;
                    }
                    //remodel 委改厂  packing 包装厂
                    //去往包装厂 或者 委改厂的车辆
                    String str2 = "";
                    if (warehouseVo!=null) {
                        List<String> list = new ArrayList<>();
                        list.add(str);
                        params.setVehicleInLocIds(list);
                        params.setCarrierNo(routVo.getCarrierNo());
                        params.setMoveToWarehouseCode(warehouseVo.getId());
                        params.setStatus(warehouseVo.getWarehouseType());
                        str2 = this.moveDispatch2(params);
                    }

                    if(warehouseVo.getWarehouseType().equals("packing")){
                        this.iExpressService.importDataWithCarrier2(data,ent,sysUser,str2);
                    }
                    //String rt=  this.iExpressService.importDataWithCarrier(data,ent,sysUser,successNum,failureNum);
                    //successMsg.append("");
                } catch (Exception e) {
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、订单号 " + data.getPurchaseOrderNo() + " 导入失败：";
                    successMsg.append(msg + e.getMessage());
                    log.error(msg, e);
                    successMsg.append(msg + e.getMessage());

                }
            }

        return result.success(successMsg.toString());
    }

    private TFoTransitRouteVo getCarrier(DispatchImportOrderItemVo data){
        TFoTransitRouteSearchParam params = new TFoTransitRouteSearchParam();
        params.setCarrierName(data.getCarrierName());
        params.setRouteType("carrierType");
        TFoTransitRouteVo tFoTransitRouteVo = iTFoTransitRouteService.findByCarrierName(params);
        return tFoTransitRouteVo;
    }

    @ApiOperation("导入承运商")
    @PostMapping("/importData1")
    public Result importData1(MultipartFile file) {
        return result.success(this.service.importData1(file));
    }



    @ApiOperation("列表-分页")
    @PreAuthorize("hasAnyAuthority('tms:tFoFreightOrderItem:search')")
    @PostMapping("/search/{current}/{pageSize}")
    public Result findAll(@RequestBody TFoFreightOrderItemSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        return result.success(this.service.findAll(params, current, pageSize));
    }

}
